<?php
namespace app\common\service;
use app\common\model\User;
use think\Db;

/**
 * 三级分销促销方案模块
 */
class Activity
{

    /**
     * 用户注册之后，确定推荐关系
     * @param $userInfo
     */
    public static function afterRegister($userInfo) {

    }


    /**
     * 存储更新我的团队数据
     * @param $username
     * @param $uid
     * @return bool
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public static function updateTeamList($username, $uid)
    {
        $sessionVisit = session('teamList');
        //10分钟内不再处理
        if (!empty($sessionVisit)) {
            $teamData = Db::name('activity_temp_team')->where(array('current_user_id' => $uid))->find();
            if (( time() - $sessionVisit < 600) && $teamData) {
                return true;
            }
        }
        $teamList = [];
        $getField = 'id as user_id,username,nickname,avatar,tjr_username,logintime,createtime,tjr_uid,tjr_num,0 as performance';
        $firstList = User::where(['tjr_username'=>$username])->field($getField.',1 as qin_mi')->select();
        $firstUsername = User::where(['tjr_username'=>$username])->column('username');

        if($firstUsername && count($firstUsername)>0) {
            $firstUsernameStr = join(',',$firstUsername);
            $secondList = User::where('tjr_username','in',$firstUsernameStr)->field($getField.',2 as qin_mi')->select();
            $secondUsername = User::where('tjr_username','in',$firstUsernameStr)->column('username');
            if ($secondUsername && count($secondUsername)>0 ) {
                //一二级会员
                $teamList = array_merge($firstList,$secondList);
                $secondUsernameStr = join(',',$secondUsername);
                $thirdList = User::where('tjr_username','in',$secondUsernameStr)->field($getField.',3 as qin_mi')->select();
                if (!empty($thirdList)) {
                    $teamList = array_merge($teamList,$thirdList);
                }
            } else {
                $teamList = $firstList;
            }
        }
        //如果没有数据直接返回
        if (empty($teamList)) return true;

        $teamList = toArray($teamList);
        $myTeamData = Db::name('activity_temp_team')->where(array('current_user_id' => $uid))->column('user_id,id');
        //注意，使用大数据写入方法，这个model要提前定义保证是一个实例。否则bSave则没有数据
        $tempTeamModel = Db::name('activity_temp_team');
        $readTime = date('Y-m-d H:i:s');
        foreach ($teamList as $item) {
            $item['current_user_id'] = $uid;
            $item['read_time'] = $readTime;
            if (isset($myTeamData[$item['user_id']])) {
                //那么更新
                $item['id'] = $myTeamData[$item['user_id']];
                $tempTeamModel->bUpdate($item);
            } else {
                //那么写入数据
                $tempTeamModel->bAdd($item);
            }
        }
        $tempTeamModel->bSave();
        //记录一个访问时间
        session('teamList',time());
    }


}